import LogFactory from "log/LogFactory";
import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {ReimburseDetailsType} from "type/ReimburseDetailsType";
import {uuid32} from "util/uuid";
import {DefaultOptionType} from "rc-select/lib/Select";
import {
    fetchAddDetailsQuery, fetchAddItemOptions,
    fetchDeleteById,
    fetchGetItemOptions,
    fetchListByReimburseId,
    fetchUpdateDetails,
    fetchUpdateItemOptions
} from "./async/detailsAsyncAction";
import {StateBaseType} from "../StateBaseType";
import {ReduxStatus} from "enum/ReduxStatus";

const log = LogFactory.getLog("Redux.reimburseDetail");


/**
 * 报销单详细信息表单的的条目渲染类型
 */
export interface DetailsOptionProps {
    key: string;
    label: string;
    value: string;
    order: number;
    /**
     * 是否隐藏
     */
    hide: boolean;
    /**
     * 是否为默认选中
     */
    defaultChecked: boolean
}

/**
 * 报销单详细信息 redux状态类型
 */
export type ReimburseDetailState = StateBaseType<ReimburseDetailsType> & {
    /**
     * 报销单id
     */
    reimburseId: number,
    /**
     * 报销单总金额
     */
    totalMoney: number,
    /**
     * 同步状态(报销记录的同步状态)
     * 0: 未同步
     * 1: 待定
     * 48: 同步成功
     */
    syncState: 0 | 1 | 48 | 50,
    /**
     * 报销单记录可用条目选项
     */
    itemOptions?: DefaultOptionType[];
    /**
     * 报销单记录可用条目选项,默认选中的条目
     */
    defaultCheckedItem?: string;
};

/**
 * 初始化的状态
 */
const initialState: ReimburseDetailState = {
    reimburseId: 0,
    data: [],
    pageSize: 10,
    //TODO: 从系统配置中获取分页数据大小,系统设置目前没有配置修改manager模块
    // pageSize: getSystemConfig().reimbursePageSize,
    current: 1,
    total: 0,
    loading: false,
    status: 0,
    totalMoney: 0,
    syncState: 0,
};

export const reimburseDetailSlice = createSlice({
    name: 'reimburseDetail',
    initialState,
    reducers: {
        deleteDetailsById: (state, action: PayloadAction<number>) => {
            // log.redux("删除报销单记录: ", action.payload) ;
            let index = state.data.findIndex(item => item.id === action.payload);
            if (index !== -1) {
                let cm = state.data[index].consumeMoney;
                state.data.splice(index, 1);
                state.totalMoney = (state.totalMoney * 1000 - cm * 1000) / 1000;
                // state.status = ReduxStatus.refresh ;
            }
            state.syncState = 50;
        },
        addDetailsData: (state, action: PayloadAction<ReimburseDetailsType>) => {
            log.debug("添加报销单记录: ", action.payload);
            action.payload.key = uuid32();
            state.data.unshift(action.payload);
            state.status = ReduxStatus.REFRESH ;
            state.totalMoney += action.payload.consumeMoney;
        },
        updateDetailsData: (state, action: PayloadAction<ReimburseDetailsType>) => {
            log.redux("修改报销单记录: ", action.payload);
            let index = state.data.findIndex(item => item.id === action.payload.id);
            if (index !== -1) {
                let m = state.data[index].consumeMoney;
                let s = (state.totalMoney * 1000 - m * 1000 + action.payload.consumeMoney * 1000) / 1000;
                state.totalMoney = s;
                state.data[index] = action.payload;
            }
        },
        updateSyncState: (state, action: PayloadAction<0 | 1 | 48>) => {
            log.redux("修改报销单记录同步状态: ", action.payload);
            state.syncState = action.payload;
        },
    },
    extraReducers: (builder) => {
        builder.addCase(fetchListByReimburseId.pending, (state) => {
            state.loading = true;
            state.status = ReduxStatus.PENDING;
        });

        builder.addCase(fetchListByReimburseId.fulfilled, (state, action) => {
            state.loading = false;
            if (action.payload.data === null) {
                log.redux("获取报销记录详细信息失败: ", action.payload);
                state.status = 5 ;
                return ;
            }
            let totalTemp = action.payload.data.reduce((accumulator, currentValue) => accumulator + currentValue.consumeMoney * 1000, 0);
            state.totalMoney = totalTemp / 1000;
            state.status = ReduxStatus.SUCCESS;
            state.data = action.payload.data;
            state.reimburseId = action.payload.reimburseId;
        });

        builder.addCase(fetchAddDetailsQuery.fulfilled, (state, action) => {
            log.redux("添加并查找报销记录信息", action.payload);
            if (action.payload.success) {
                state.data.unshift(action.payload.data);
                state.totalMoney += action.payload.data.consumeMoney;
            }
        });

        /**
         * 获取报销记录可用item条目选项
         */
        builder.addCase(fetchGetItemOptions.fulfilled, (state, action) => {
            log.redux("获取报销记录可用item条目选项: ", action.payload.data);
            if (action.payload.success && action.payload.data.length > 0) {
                state.itemOptions = action.payload.data.filter(item => {
                    item.defaultChecked && (state.defaultCheckedItem = item.value);
                    return !item.hide ;
                }) ;
            }
        });

        builder.addCase(fetchUpdateItemOptions.fulfilled,(state,action) => {
            log.redux("更新报销记录可用item条目选项",action) ;

        }) ;

        builder.addCase(fetchUpdateDetails.fulfilled, (state, action) => {
            log.redux("更新报销记录详细信息: ", action.payload);
            let {consumeMoney, consumeDate, remark, item} = action.payload.details;
            if (action.payload.data > 0) {
                let index = state.data.findIndex(item => item.id === action.payload.details.id);
                if (index !== -1) {
                    if (consumeMoney){
                        let m = state.data[index].consumeMoney;
                        state.totalMoney = (state.totalMoney * 1000 - m * 1000 + action.payload.details.consumeMoney * 1000) / 1000;
                        state.data[index].consumeMoney = consumeMoney
                    }
                    consumeDate && (state.data[index].consumeDate = consumeDate);
                    item && (state.data[index].item = item);
                    remark && (state.data[index].remark = remark);
                }
            }
        });

        /**
         * 删除报销记录,根据id
         */
        builder.addCase(fetchDeleteById.fulfilled, (state, action) => {
            if (action.payload.data > 0) {
                log.redux("删除报销记录成功: ", action.payload);
                let index = state.data.findIndex(item => item.id === action.payload.id);
                if (index !== -1) {
                    let cm = state.data[index].consumeMoney;
                    state.data.splice(index, 1);
                    state.totalMoney = (state.totalMoney * 1000 - cm * 1000) / 1000;
                    state.syncState = 48;
                }
            } else {
                log.warn("删除报销记录失败: ", action.payload);
            }
        });

        builder.addCase(fetchAddItemOptions.fulfilled,(state, action)=>{
            log.redux("添加报销记录选项") ;
            if (action.payload.data > 0){
                state.itemOptions?.push({label: action.payload.value,value: action.payload.value});
            }
        });
    }
});

export const {deleteDetailsById, addDetailsData, updateDetailsData, updateSyncState} = reimburseDetailSlice.actions;

export default reimburseDetailSlice.reducer;